<!-- 
  编辑表单组件
  
  高亮逻辑说明：
  - 本组件通过事件总线与主地图组件通信
  - 使用 UPDATE_SELECTED_BUILDINGS 事件更新建筑物高亮样式
  - 使用 CLEAR_SELECTED_BUILDINGS 事件清除建筑物高亮样式
  - 与重构后的特殊图层高亮逻辑完全兼容
  - 支持建筑物选择、点位添加、GeoJSON 高亮等功能
-->

<template>
  <div class="edit-mode">
    <div class="edit-header">
      <div class="edit-title">
        <span
          class="edit-title-text"
          :title="
            editingItem
              ? editingItem.name || editingItem.communityName
              : '新增项目'
          "
        >
          {{
            editingItem
              ? editingItem.name || editingItem.communityName
              : '新增项目'
          }}
        </span>
        <span
          class="edit-status"
          :style="{
            backgroundColor: statusOptions.find(
              (option) => option.value == editingItem.status
            )?.color,
          }"
          v-if="editingItem"
          >{{
            statusOptions.find((option) => option.value == editingItem.status)
              ?.label
          }}</span
        >
      </div>

      <div class="edit-actions">
        <el-popconfirm 
          title="确定删除吗？" 
          @confirm="handleDelete"
          :key="`delete-${detailMode}-${!!editingItem}`"
        >
          <el-button
            type="danger"
            size="mini"
            slot="reference"
            v-if="editingItem && !detailMode"
            icon="el-icon-delete"
            circle
            :key="`delete-btn-${detailMode}-${!!editingItem}`"
          ></el-button>
        </el-popconfirm>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-edit-outline"
          circle
          @click="handleEdit"
          v-if="templateId !== '1z' && detailMode && type !== 'sq'"
        ></el-button>
        <el-button
          type="default"
          size="mini"
          icon="el-icon-back"
          circle
          @click="handleCancel"
        ></el-button>
      </div>
    </div>
    <div class="edit-form-container">
    <el-form
      ref="editFormRef"
      :model="formData"
      :rules="formRules"
      class="edit-form"
      label-position="top"
    >
      <template v-for="item in formItems">
        <el-form-item
          v-if="item.type === 'input' && shouldShowChildItem(item)"
          :key="`input-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-input
              v-model="formData[item.pkid]"
              :placeholder="item.hint"
              :type="
                item.problemType === '13' || item.problemType === '14'
                  ? 'number'
                  : 'text'
              "
              clearable
            >
              <template v-if="item.unit" #suffix>{{ item.unit }}</template>
            </el-input>
          </template>
          <template v-else>
            <span>{{ formData[item.pkid] || '-' }}</span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'textarea' && shouldShowChildItem(item)"
          :key="`textarea-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-input
              v-model="formData[item.pkid]"
              type="textarea"
              :rows="3"
              :placeholder="item.hint"
              clearable
            />
          </template>
          <template v-else>
            <span style="white-space: pre-line">{{
              formData[item.pkid] || '-'
            }}</span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'radio' && shouldShowChildItem(item)"
          :key="`radio-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-radio-group v-model="formData[item.pkid]">
              <el-radio
                v-for="option in item.problemContentInfoList"
                :key="option.pkid"
                :label="option.pkid"
              >
                {{ option.content }}
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else>
            <span>
              {{
                (
                  item.problemContentInfoList.find(
                    (opt) => opt.pkid == formData[item.pkid]
                  ) || {}
                ).content || '-'
              }}
            </span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'checkbox' && shouldShowChildItem(item)"
          :key="`checkbox-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-checkbox-group v-model="formData[item.pkid]">
              <el-checkbox
                v-for="option in item.problemContentInfoList"
                :key="option.pkid"
                :label="option.pkid"
              >
                {{ option.content }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
          <template v-else>
            <span>
              <template
                v-if="
                  Array.isArray(formData[item.pkid]) &&
                  formData[item.pkid].length
                "
              >
                {{
                  formData[item.pkid]
                    .map(
                      (val) =>
                        (
                          item.problemContentInfoList.find(
                            (opt) => opt.pkid == val
                          ) || {}
                        ).content
                    )
                    .filter(Boolean)
                    .join('，')
                }}
              </template>
              <template v-else>-</template>
            </span>
          </template>
        </el-form-item>
        <el-form-item
          v-if="item.type === 'date-picker' && shouldShowChildItem(item)"
          :key="`date-picker-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-date-picker
              v-model="formData[item.pkid]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="item.hint"
              clearable
            >
            </el-date-picker>
          </template>
          <template v-else>
            <span>{{ formData[item.pkid] || '-' }}</span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'image-upload' && shouldShowChildItem(item)"
          :key="`image-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-upload
              action=""
              list-type="picture-card"
              :file-list="formData[item.pkid] || []"
              :http-request="() => {}"
              :before-upload="beforeImageUpload"
              :on-change="
                (file, fileList) => handleImageChange(file, fileList, item.pkid)
              "
              :on-remove="(file) => handleImageRemove(file, item.pkid)"
              :multiple="true"
              :auto-upload="false"
              accept="image/*"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- <div v-if="item.limitCondition" class="upload-limit">
              至少上传 {{ item.limitCondition }} 张照片
            </div> -->
            <div v-if="item.hint" class="upload-limit">
              {{item.hint}}
            </div>
          </template>
          <template v-else>
            <div v-if="formData[item.pkid] && formData[item.pkid].length">
              <el-image
                v-for="img in formData[item.pkid]"
                :key="img.id"
                :src="img.url"
                style="width: 80px; margin-right: 8px"
                :preview-src-list="formData[item.pkid].map((i) => i.url)"
              />
            </div>
            <span v-else>无</span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'draw' && shouldShowChildItem(item)"
          :key="`draw-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <div>
              <el-button type="primary" @click="() => handleStartDraw(item)">
                {{ formData[item.pkid] ? '重新绘制' : item.hint }}
              </el-button>
              <el-button type="success" @click="() => handleDrawEnd()">完成绘制</el-button>
            </div>
            <div>
                              <el-button type="default" @click="() => handleClearDraw(item)" v-if="['8', '10'].includes(item.problemType) && hasSelectedDrawFeatures">清除绘制</el-button>
                <el-button type="default" @click="() => handleClearAllDraw(item)" v-if="['8', '10'].includes(item.problemType)">清除全部</el-button>
              <span v-if="formData[item.pkid]" class="draw-info">
                <span>{{ getDrawStatusText(item) }} </span>
                <!-- <span>
                  <el-button type="text" @click="handleViewDraw(item)">
                    <i>查看</i>
                  </el-button>
                </span> -->
             </span>
            </div>
          </template>
          <template v-else>
            <span v-if="formData[item.pkid]">{{
              getDrawStatusText(item)
            }}</span>
            <span v-else>-</span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'building-choose' && shouldShowChildItem(item)"
          :key="`building-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <div class="building-selection-container">
              <el-button
                type="primary"
                @click="() => handleChooseBuilding(item)"
                :disabled="
                  isBuildingSelectionMode &&
                  currentBuildingItem &&
                  currentBuildingItem.pkid !== item.pkid
                "
              >
                {{ formData[item.pkid] ? '重新选择' : item.hint }}
              </el-button>
              <el-button
                v-if="
                  isBuildingSelectionMode &&
                  currentBuildingItem &&
                  currentBuildingItem.pkid === item.pkid
                "
                type="success"
                @click="() => handleCompleteBuildingSelection(item)"
                style="margin-left: 10px"
              >
                完成选中
              </el-button>
              <el-button
                v-if="
                  isBuildingSelectionMode &&
                  currentBuildingItem &&
                  currentBuildingItem.pkid === item.pkid
                "
                type="default"
                @click="handleCancelBuildingSelection"
                style="margin-left: 10px"
              >
                清空选择
              </el-button>
              <span v-if="isBuildingSelectionMode && currentBuildingItem && currentBuildingItem.pkid === item.pkid && (selectedBuildings.length > 0 || buildingPoints.length > 0)" class="building-info">
                <span v-if="selectedBuildings.length > 0">
                  已选择{{ item.problemType === '30' ? '多个' : '' }}建筑 ({{
                    selectedBuildings.length
                  }}个)
                </span>
                <span v-if="buildingPoints.length > 0" :style="selectedBuildings.length > 0 ? 'margin-left: 10px' : ''">
                  已添加点位 ({{ buildingPoints.length }}个)
                </span>
              </span>
              <span v-else-if="formData[item.pkid] && (getBuildingCount(item.pkid) > 0 || getPointCount(item.pkid) > 0)" class="building-info">
                <span v-if="getBuildingCount(item.pkid) > 0">
                  已选择{{ item.problemType === '30' ? '多个' : '' }}建筑 ({{
                    getBuildingCount(item.pkid)
                  }}个)
                </span>
                <span v-if="getPointCount(item.pkid) > 0" :style="getBuildingCount(item.pkid) > 0 ? 'margin-left: 10px' : ''">
                  已添加点位 ({{ getPointCount(item.pkid) }}个)
                </span>
              </span>
            </div>
          </template>
          <template v-else>
            <span>
              <template
                v-if="formData[item.pkid] && (getBuildingCount(item.pkid) > 0 || getPointCount(item.pkid) > 0)"
              >
                <span v-if="getBuildingCount(item.pkid) > 0">
                  已选择{{ item.problemType === '30' ? '多个' : '' }}建筑 ({{
                    getBuildingCount(item.pkid)
                  }}个)
                </span>
                <span v-if="getPointCount(item.pkid) > 0" :style="getBuildingCount(item.pkid) > 0 ? 'margin-left: 10px' : ''">
                  已添加点位 ({{ getPointCount(item.pkid) }}个)
                </span>
              </template>
              <template v-else>-</template>
            </span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'floor-choose' && shouldShowChildItem(item)"
          :key="`floor-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-button type="primary" @click="() => handleChooseFloor(item)">
              {{ formData[item.pkid] ? '重新选择' : item.hint }}
            </el-button>
            <span v-if="formData[item.pkid]" class="floor-info">
              已选择楼层
            </span>
          </template>
          <template v-else>
            <span v-if="formData[item.pkid]">已选择楼层</span>
            <span v-else>-</span>
          </template>
        </el-form-item>

        <el-form-item
          v-if="item.type === 'region-select' && shouldShowChildItem(item)"
          :key="`region-${item.pkid}`"
          :prop="item.pkid"
          :label="item.problemContent"
        >
          <template v-if="!detailMode">
            <el-cascader
              v-model="formData[item.pkid]"
              :options="item.areaList || cityOptions"
              :props="cascaderProps"
              :placeholder="item.hint"
              clearable
              filterable
              :show-all-levels="false"
            />
          </template>
          <template v-else>
            <span>
              <template
                v-if="
                  Array.isArray(formData[item.pkid]) &&
                  formData[item.pkid].length
                "
              >
                {{ getRegionLabel(item, formData[item.pkid]) }}
              </template>
              <template v-else>-</template>
            </span>
          </template>
        </el-form-item>
      </template>

      <div class="form-actions" v-if="!detailMode">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleTemporarySave">暂存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-form>
    </div>
    <!-- <DrawMap
      :visible="showDrawTool"
      title="位置绘制"
      :type="currentDrawItem?.problemType"
      :data="getDrawMapData()"
      @update="handleDrawEnd"
      @close="handleCloseDrawTool"
    /> -->
    <DrawMapTool
      :visible="showDrawTool"
      ref="drawMapToolRef"
      title="位置绘制"
      :data="getDrawMapData()"
      :type="currentDrawItem?.problemType"
      :templateId="templateId"
      @close="handleCloseDrawTool"
    />
  
  </div>
</template>

<script>
import { Message } from 'element-ui'
// import DrawMap from '@/components/draw-map'
import { uploadFiles } from '@/api/question'
import emitter from '@/utils/event-bus'
import { template } from '@/utils/radash'
import DrawMapTool from './components/draw-map-tool.vue'

export default {
  name: 'EditForm',
  components: {
    // DrawMap,
    DrawMapTool,
  },
  props: {
    editingItem: {
      type: Object,
      default: null,
    },
    cityOptions: {
      type: Array,
      default: () => [],
    },
    statusOptions: {
      type: Array,
      default: () => [],
    },
    detailMode: {
      type: Boolean,
      default: false,
    },
    templateId: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      cascaderProps: {
        value: 'pkid',
        label: 'areaName',
        checkStrictly: true,
        children: 'children',
      },
      problemTypeMap: {
        1: 'input', // 普通文本输入
        2: 'radio', // 单选
        3: 'checkbox', // 多选
        4: 'image-upload', // 图片上传
        7: 'textarea', // 多行文本输入
        8: 'draw', // 绘制多线
        10: 'draw', // 绘制多面
        11: 'building-choose', // 选择建筑物或楼栋-单个
        13: 'input', // 整数数字输入
        14: 'input', // 小数数字输入
        24: 'draw', // 绘制多点
        25: 'date-picker', // 日期选择
        26: 'region-select', // 级联筛选-行政区划选择-社区级别
        27: 'floor-choose', // 楼层选择
        28: 'region-select', // 级联筛选-行政区划选择-区级别
        29: 'region-select', // 级联筛选-行政区划选择-街道级别
        30: 'building-choose', // 选择建筑物或楼栋-多个
      },
      // 动态表单数据
      formData: {},
      formItems: [],
      formRules: {},
      showDrawTool: false,
      currentDrawItem: null,
      isBuildingSelectionMode: false,
      currentBuildingItem: null,
      selectedBuildings: [],
      buildingPoints: [], // 存储建筑物选择模式下的点位
      specialLayerWasChecked: false,
      pendingUploads: {}, // 存储待上传的文件
      activeGeoJson: null,
      activeBuildingIds: null,
      activeMarkers: null, // 新增
      initDrawData: [], // 用于记录初始化进入时地图选中模块
      historySelectedIds: null, //曾经选中的建筑id
      hasSelectedDrawFeatures: false, // 是否有选中的绘制要素
    }
  },
  watch: {
    formData: {
      handler(newVal, oldVal) {
        this.$forceUpdate()
      },
      deep: true,
    },
    templateId: {
      handler(newVal) {
        
      },
      immediate: true,
    },
  },
  methods: {
    openBuildingMode() {
      emitter.emit('ENABLE_BUILDING_CLICK')
    },
    closeBuildingMode() {
      emitter.emit('DISABLE_BUILDING_CLICK')
    },
    noneClick() {
      emitter.emit('NONE_CLICK')
    },
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        Message.error('只能上传图片文件!')
        return false
      }

      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        Message.error('图片大小不能超过 5MB!')
        return false
      }

      return false // 阻止自动上传
    },
    handleImageChange(file, fileList, fieldId) {
      // 过滤出新添加的文件（状态为 'ready' 的文件）
      const newFiles = fileList.filter((f) => f.status === 'ready' && f.raw)

      if (newFiles.length === 0) return

      // 清除之前的定时器
      if (this.pendingUploads[fieldId]) {
        clearTimeout(this.pendingUploads[fieldId].timer)
      }

      // 设置定时器，延迟执行上传
      this.pendingUploads[fieldId] = {
        files: newFiles,
        timer: setTimeout(() => {
          this.uploadBatchImages(newFiles, fieldId)
          delete this.pendingUploads[fieldId]
        }, 300), // 300ms 延迟，确保所有文件都添加完成
      }
    },
    async uploadBatchImages(files, fieldId) {
      const validFiles = files
        .map((f) => f.raw)
        .filter((file) => {
          return file.type.startsWith('image/') && file.size / 1024 / 1024 < 5
        })

      if (validFiles.length === 0) {
        Message.error('没有有效的图片文件!')
        return
      }

      try {
        const formData = new FormData()
        validFiles.forEach((validFile) => {
          formData.append('files', validFile)
        })
        formData.append('type', 'xcx')

        const response = await uploadFiles(formData)

        if (response.success && response.data) {
          if (!Array.isArray(this.formData[fieldId])) {
            this.formData[fieldId] = []
          }

          const newFiles = Array.isArray(response.data)
            ? response.data
            : [response.data]

          newFiles.forEach((fileId, index) => {
            const currentFile = validFiles[index]
            if (currentFile && fileId) {
              this.formData[fieldId].push({
                name: currentFile.name,
                url: URL.createObjectURL(currentFile),
                uid: files[index].uid,
                id: fileId,
              })
            }
          })

          Message.success(`成功上传 ${validFiles.length} 张照片!`)
        } else {
          Message.error(response.message || '上传失败')
        }
      } catch (error) {
        Message.error('上传失败，请重试')
      }
    },

    handleImageRemove(file, fieldId) {
      const index = this.formData?.[fieldId]?.findIndex(
        (item) => item.uid === file.uid
      )
      if (index > -1) {
        this.formData[fieldId].splice(index, 1)
        Message.success('照片删除成功!')
      }
    },

    handleStartDraw(item) {
      // 设置当前绘制项
      // this.currentDrawItem = item
      
      // 启用编辑模式
      if (this.$refs.drawMapToolRef) {
        this.$refs.drawMapToolRef.setEditMode(true)
      }
      
      switch (item.problemType) {
        case '8':
          this.$refs.drawMapToolRef.addDraw('polyline')
          break
        case '10':
          this.$refs.drawMapToolRef.addDraw('polygon')
          break
        case '24':
          this.$refs.drawMapToolRef.addDraw('point')
          break
      }
      this.showDrawTool = true
      
      // 添加选择事件监听器
      this.addDrawSelectionListeners()
    },

    handleViewDraw(item) {

      // this.currentDrawItem = item
      // this.showDrawTool = true
    },

    handleDrawEnd() {
      if (!this.currentDrawItem) return
     
      // 从draw-map-tool获取当前绘制数据
      const drawData = this.$refs.drawMapToolRef?.getDrawResult()
      if (!drawData) {
        Message.info('未绘制任何图形')
        this.showDrawTool = false
        this.currentDrawItem = null
        return
      }

      const { wgsPosition, lineWgsPosition, pointWgsPosition } = drawData
      let featureCount = 0
      let positionInfo = []
      let geoJsonFeature = null

      switch (this.currentDrawItem.problemType) {
        case '8':
          if (lineWgsPosition) {
            const lines = JSON.parse(lineWgsPosition)
            featureCount = lines.length

            geoJsonFeature = {
              type: 'Feature',
              properties: {},
              geometry: {
                type: lines.length === 1 ? 'LineString' : 'MultiLineString',
                coordinates: lines.length === 1 ? lines[0] : lines,
              },
            }

            positionInfo.push(`${lines.length} 条线`)
          }
          break
        case '10':
          if (wgsPosition) {
            const polygons = JSON.parse(wgsPosition)
            featureCount = polygons.length
            geoJsonFeature = {
              type: 'Feature',
              properties: {},
              geometry: {
                type: polygons.length === 1 ? 'Polygon' : 'MultiPolygon',
                coordinates:
                  polygons.length === 1
                    ? [polygons[0]]
                    : polygons.map((poly) => [poly]),
              },
            }
            positionInfo.push(`${polygons.length} 个面`)
          }
          break
        case '24':
          if (pointWgsPosition) {
            const points = JSON.parse(pointWgsPosition)
            featureCount = points.length

            const coordinates = points.map((point) => {
              if (Array.isArray(point) && point.length >= 2) {
                return [parseFloat(point[0]), parseFloat(point[1])]
              }
              return point
            })

            geoJsonFeature = {
              type: 'Feature',
              properties: {},
              geometry: {
                type: coordinates.length === 1 ? 'Point' : 'MultiPoint',
                coordinates:
                  coordinates.length === 1 ? coordinates[0] : coordinates,
              },
            }
            positionInfo.push(`${coordinates.length} 个点`)
          }
          break
      }

      if (featureCount > 0 && geoJsonFeature) {
        this.formData[this.currentDrawItem.pkid] = geoJsonFeature
        Message.success(`成功绘制 ${positionInfo.join('、')}`)
      } else {
        this.formData[this.currentDrawItem.pkid] = ''
        Message.info('未绘制任何图形')
      }

      this.showDrawTool = false
      this.currentDrawItem = null
      
      // 移除选择事件监听器
      this.removeDrawSelectionListeners()
      // 重置选中状态
      this.hasSelectedDrawFeatures = false
    },

    handleChooseBuilding(item) {
      this.openBuildingMode()
      if (this.isBuildingSelectionMode) {
        this.exitBuildingSelectionMode()
      }

      this.currentBuildingItem = item

      // 如果是重新选择，恢复之前选中的楼栋和点位
      if (this.formData[item.pkid] && this.formData[item.pkid][0]) {
        const previousData = this.formData[item.pkid][0]
        const previousBuildingIds = previousData.buildings || []
        const previousPoints = previousData.points || []
        
        // 恢复 selectedBuildings 数组，确保id格式一致
        this.selectedBuildings = previousBuildingIds.map(id => ({ 
          id: String(id) // 确保ID是字符串格式
        }))
        
        // 恢复点位数据
        this.buildingPoints = previousPoints.map((point, index) => ({
          coordinates: point,
          id: Date.now() + index
        }))
        
        // 更新地图上的高亮样式，确保ID格式一致
        if (previousBuildingIds.length > 0) {
          const stringIds = previousBuildingIds.map(id => String(id))
          emitter.emit('UPDATE_SELECTED_BUILDINGS', {
            buildingIds: stringIds,
            deleteIds: []
          })
        }
        
        // 更新地图上的点位显示
        if (this.buildingPoints.length > 0) {
          emitter.emit('UPDATE_BUILDING_POINTS', {
            points: this.buildingPoints,
            deletePoint: null
          })
        }
      } else {
        this.selectedBuildings = []
        this.buildingPoints = []
      }

      this.checkAndToggleSpecialLayer()

      this.isBuildingSelectionMode = true

      this.bindMapClickForBuildingSelection()

    },

    handleChooseFloor(item) {

    },

    checkAndToggleSpecialLayer() {
      emitter.emit('CHECK_SPECIAL_LAYER_STATUS', (isChecked) => {
        this.specialLayerWasChecked = isChecked
        if (isChecked) {
          Message.info('请在地图上点击选择楼栋，再次点击可取消选中，选择完成后点击"完成选中"按钮')
        }
        if (!isChecked) {
          emitter.emit('TOGGLE_SPECIAL_LAYER', true)
          // 等待特殊图层加载完成后，应用高亮样式
          setTimeout(() => {
            // 如果有已选择的建筑物，重新应用高亮
            if (this.selectedBuildings.length > 0) {
              const buildingIds = this.selectedBuildings.map(building => String(building.id))
              emitter.emit('UPDATE_SELECTED_BUILDINGS', {
                buildingIds,
                deleteIds: []
              })
            }
            // 显示选择提示
            Message.info('请在地图上点击选择楼栋，再次点击可取消选中，选择完成后点击"完成选中"按钮')
          }, 1500) // 给特殊图层加载一些时间
        }
      })
    },

    bindMapClickForBuildingSelection() {
      this.unbindMapClickForBuildingSelection()
      emitter.on('MAP_BUILDING_CLICK', this.handleBuildingClick)
      emitter.on('MAP_BLANK_CLICK', this.handleMapBlankClick)
      emitter.on('BUILDING_POINT_CLICK', this.handleBuildingPointClick)
    },

    unbindMapClickForBuildingSelection() {
      emitter.off('MAP_BUILDING_CLICK', this.handleBuildingClick)
      emitter.off('MAP_BLANK_CLICK', this.handleMapBlankClick)
      emitter.off('BUILDING_POINT_CLICK', this.handleBuildingPointClick)
    },

    handleBuildingClick(buildingData) {
      if (!this.isBuildingSelectionMode) return
       
      const existingIndex = this.selectedBuildings.findIndex(
        (building) => String(building.id) === String(buildingData.id)
      )

      if (existingIndex > -1) {
        this.selectedBuildings.splice(existingIndex, 1)
      } else {
        this.selectedBuildings.push(buildingData)
      }

      if (
        this.currentBuildingItem.problemType === '11' &&
        this.selectedBuildings.length > 1
      ) {
        this.selectedBuildings = [
          this.selectedBuildings[this.selectedBuildings.length - 1],
        ]
      }

      const buildingIds = this.selectedBuildings.map((building) => String(building.id))
      const initBuildingIds = this.initDrawData.flatMap(item => item.buildings || []).map(String);
      if (!this.historySelectedIds) {
        this.historySelectedIds = new Set(initBuildingIds);
      }

      for (const id of buildingIds) {
        this.historySelectedIds.add(id);
      }
      const deleteIds = Array.from(this.historySelectedIds).filter(id => !buildingIds.includes(id));
      emitter.emit('UPDATE_SELECTED_BUILDINGS', {
        buildingIds,
        deleteIds
      })
      // 更新label图层
      this.$nextTick(() => {
        emitter.emit('UPDATE_LABEL_LAYER')
      })
    },
    
    handleMapBlankClick(lngLat) {
      if (!this.isBuildingSelectionMode) return
      
      // 在空白处点击，添加点位
      const newPoint = {
        coordinates: [lngLat.lng, lngLat.lat],
        id: Date.now()
      }
      this.buildingPoints.push(newPoint)
      
      // 更新地图上的点位显示
      emitter.emit('UPDATE_BUILDING_POINTS', {
        points: this.buildingPoints,
        deletePoint: null
      })
    },
    
    handleBuildingPointClick(clickedPointData) {
      if (!this.isBuildingSelectionMode) return
      
      const { coordinates, properties } = clickedPointData
      
      // 检查是否是新增的点位（没有pkid等原始属性）
      const isNewPoint = !properties.pkid && !properties.templateId
      if (isNewPoint) {
        // 新增的点位：直接删除
        const tolerance = 0.0001 // 约10米的精度
        const index = this.buildingPoints.findIndex(point => {
          const dx = Math.abs(point.coordinates[0] - coordinates[0])
          const dy = Math.abs(point.coordinates[1] - coordinates[1])
          return dx < tolerance && dy < tolerance
        })
        if (index > -1) {
          const deletedPoint = this.buildingPoints[index]
          this.buildingPoints.splice(index, 1)
          emitter.emit('UPDATE_BUILDING_POINTS', {
            points: this.buildingPoints,
            deletePoint: deletedPoint
          })
           // 更新label图层
          this.$nextTick(() => {
            emitter.emit('UPDATE_LABEL_LAYER')
          })
        }
      } else {
        // 现有点位：切换高亮状态
        const tolerance = 0.0001 // 约10米的精度
        const index = this.buildingPoints.findIndex(point => {
          const dx = Math.abs(point.coordinates[0] - coordinates[0])
          const dy = Math.abs(point.coordinates[1] - coordinates[1])
          return dx < tolerance && dy < tolerance
        })
       
        if (index > -1) {
          const deletedPoint = this.buildingPoints[index]
          this.buildingPoints.splice(index, 1)
          emitter.emit('UPDATE_BUILDING_POINTS', {
            points: this.buildingPoints,
            deletePoint: deletedPoint
          })
          // 更新label图层
          this.$nextTick(() => {
            emitter.emit('UPDATE_LABEL_LAYER')
          })
        } else {
          // 如果点位不在buildingPoints中（非高亮状态），则添加（高亮）
          const pointToAdd = {
            id: properties.id,
            pkid: properties.pkid,
            templateId: properties.templateId,
            name: properties.name,
            coordinates: coordinates,
            properties: properties
          }
          this.buildingPoints.push(pointToAdd)
          emitter.emit('UPDATE_BUILDING_POINTS', {
            points: this.buildingPoints,
            deletePoint: null
          })
        }
      }
    },

    handleCompleteBuildingSelection(item) {
      this.closeBuildingMode()
      const buildSelectIds = this.selectedBuildings.map(
        (building) => building.id
      )
      const pointCoordinates = this.buildingPoints.map(point => point.coordinates)
      
      this.formData[this.currentBuildingItem.pkid] = [
        { buildings: buildSelectIds, points: pointCoordinates },
      ]

      // 先保持高亮样式
      if (buildSelectIds.length > 0) {
        // 确保ID是字符串格式
        const stringIds = buildSelectIds.map(id => String(id))
        emitter.emit('UPDATE_SELECTED_BUILDINGS', {
          buildingIds: stringIds,
          deleteIds: []
        })
      }
      if (this.buildingPoints.length > 0) {
        emitter.emit('UPDATE_BUILDING_POINTS', {
          points: this.buildingPoints,
          deletePoint: null
        })
      }
      
      this.exitBuildingSelectionMode(true) // 保持点位显示
      
      const messages = []
      if (this.selectedBuildings.length > 0) {
        messages.push(`${this.selectedBuildings.length} 个楼栋`)
      }
      if (this.buildingPoints.length > 0) {
        messages.push(`${this.buildingPoints.length} 个点位`)
      }
      
      if (messages.length > 0) {
        Message.success(`已选择 ${messages.join(' 和 ')}`)
      } else {
        Message.warning('请至少选择一个楼栋或添加一个点位')
      }
    },

    handleCancelBuildingSelection() {
      emitter.emit('CLEAR_SELECTED_BUILDINGS')
      emitter.emit('CLEAR_BUILDING_POINTS')

      this.selectedBuildings = []
      this.buildingPoints = []

      Message.info('已清空选择')
    },

    exitBuildingSelectionMode(keepPointsDisplay = false) {
      this.isBuildingSelectionMode = false
      this.currentBuildingItem = null
      this.unbindMapClickForBuildingSelection()
      
      // 如果不需要保持点位显示，则清除
      if (!keepPointsDisplay) {
        emitter.emit('CLEAR_BUILDING_POINTS')
      }
      this.buildingPoints = []
    },

    getBuildingCount(fieldId) {
      const data = this.formData[fieldId]
      if (!data) return 0

      try {
        const buildings = data[0].buildings
        return Array.isArray(buildings) ? buildings.length : 0
      } catch (e) {
        return 0
      }
    },
    
    getPointCount(fieldId) {
      const data = this.formData[fieldId]
      if (!data) return 0

      try {
        const points = data[0].points
        return Array.isArray(points) ? points.length : 0
      } catch (e) {
        return 0
      }
    },
    handleTemporarySave() {
      emitter.emit('CLEAR_SELECTED_BUILDINGS')
      if (!this.specialLayerWasChecked) {
        emitter.emit('TOGGLE_SPECIAL_LAYER', false)
      }

      if (this.isBuildingSelectionMode) {
        this.exitBuildingSelectionMode()
      }

      const formatData = { ...this.formData }
      this.formItems.forEach((item) => {
        if (
          ['checkbox', 'region-select'].includes(item.type) &&
          Array.isArray(formatData[item.pkid])
        ) {
          formatData[item.pkid] = formatData[item.pkid].join(',')
        }
        if (
          item.type === 'image-upload' &&
          Array.isArray(formatData[item.pkid])
        ) {
          formatData[item.pkid] = formatData[item.pkid]
            .map((img) => img.id)
            .join(',')
        }
      })

      this.$emit('temporarySave', formatData)
    },

    handleSave() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          // emitter.emit('REMOVE_SELECTED_BUILDINGS')
          emitter.emit('CLEAR_SELECTED_BUILDINGS')
          if (!this.specialLayerWasChecked) {
            emitter.emit('TOGGLE_SPECIAL_LAYER', false)
          }

          if (this.isBuildingSelectionMode) {
            this.exitBuildingSelectionMode()
          }

          const formatData = { ...this.formData }
          this.formItems.forEach((item) => {
            if (
              ['checkbox', 'region-select'].includes(item.type) &&
              Array.isArray(formatData[item.pkid])
            ) {
              formatData[item.pkid] = formatData[item.pkid].join(',')
            }
            if (
              item.type === 'image-upload' &&
              Array.isArray(formatData[item.pkid])
            ) {
              formatData[item.pkid] = formatData[item.pkid]
                .map((img) => img.id)
                .join(',')
            }
          })

          this.$emit('save', formatData)
        } else {
          Message.error('请检查表单输入！')
          return false
        }
      })
    },

    handleDelete() {
      this.$emit('delete')
    },

    handleEdit() {
      this.$emit('edit', this.editingItem)
    },

    handleCancel() {
      this.clearGeoJsonHighlight()
      this.clearBuildingHighlight()
      this.clearMarkerHighlight() // 新增
      // this.refreshMapLayer()
      this.$emit('cancel')
    },

    resetForm() {
      this.formData = {}
      this.formItems = []
      this.formRules = {}
      this.$nextTick(() => {
        if (this.$refs.editFormRef) {
          this.$refs.editFormRef.clearValidate()
        }
      })
    },

    handleCloseDrawTool() {
      this.showDrawTool = false
      // 禁用编辑模式
      if (this.$refs.drawMapToolRef) {
        this.$refs.drawMapToolRef.setEditMode(false)
      }
      // 移除选择事件监听器
      this.removeDrawSelectionListeners()
      // 重置选中状态
      this.hasSelectedDrawFeatures = false
    },

    getDrawMapData() {

      if (!this.currentDrawItem) return {}

      const fieldValue = this.formData[this.currentDrawItem.pkid]
      if (!fieldValue) return {}

      // 如果是 GeoJSON Feature 对象，转换为对应的位置格式
      if (typeof fieldValue === 'object' && fieldValue.type === 'Feature') {
        const geometry = fieldValue.geometry

        switch (this.currentDrawItem.problemType) {
          case '8': // 多线
            if (geometry.type === 'LineString') {
              return { lineWgsPosition: JSON.stringify([geometry.coordinates]) }
            } else if (geometry.type === 'MultiLineString') {
              return { lineWgsPosition: JSON.stringify(geometry.coordinates) }
            }
            break
          case '10': // 多面
            if (geometry.type === 'Polygon') {
              return { wgsPosition: JSON.stringify([geometry.coordinates[0]]) }
            } else if (geometry.type === 'MultiPolygon') {
              return {
                wgsPosition: JSON.stringify(
                  geometry.coordinates.map((poly) => poly[0])
                ),
              }
            }
            break
          case '24': // 多点
            if (geometry.type === 'Point') {
              return {
                pointWgsPosition: JSON.stringify([geometry.coordinates]),
              }
            } else if (geometry.type === 'MultiPoint') {
              return { pointWgsPosition: JSON.stringify(geometry.coordinates) }
            }
            break
        }

        // 如果无法转换，仍然传递原始 GeoJSON
        return { geoJsonData: fieldValue }
      }

      // 如果是字符串，尝试解析
      if (typeof fieldValue === 'string') {
        try {
          const parsedValue = JSON.parse(fieldValue)
          if (parsedValue && parsedValue.type === 'Feature') {
            this.formData[this.currentDrawItem.pkid] = parsedValue
            return this.getDrawMapData()
          } else if (Array.isArray(parsedValue)) {
            switch (this.currentDrawItem.problemType) {
              case '8':
                return { lineWgsPosition: fieldValue }
              case '10':
                return { wgsPosition: fieldValue }
              case '24':
                return { pointWgsPosition: fieldValue }
              default:
                return {}
            }
          }
        } catch (e) {
          console.warn('Failed to parse draw data:', fieldValue)
        }
      }

      return {}
    },

    // 获取绘制状态文本
    getDrawStatusText(item) {
      const fieldValue = this.formData[item.pkid]
      if (!fieldValue) return ''

      try {
        let geoJsonData = null

        // 如果是 GeoJSON Feature 对象
        if (typeof fieldValue === 'object' && fieldValue.type === 'Feature') {
          geoJsonData = fieldValue
        }
        // 如果是字符串，尝试解析
        else if (typeof fieldValue === 'string') {
          const parsedValue = JSON.parse(fieldValue)
          if (parsedValue && parsedValue.type === 'Feature') {
            geoJsonData = parsedValue
          }
        }

        // 如果是 GeoJSON 格式，解析几何图形数量
        if (geoJsonData && geoJsonData.geometry) {
          const geometry = geoJsonData.geometry

          switch (geometry.type) {
            case 'Point':
              return '已绘制 1 个点'
            case 'MultiPoint':
              return `已绘制 ${geometry.coordinates.length} 个点`
            case 'LineString':
              return '已绘制 1 条线'
            case 'MultiLineString':
              return `已绘制 ${geometry.coordinates.length} 条线`
            case 'Polygon':
              return '已绘制 1 个面'
            case 'MultiPolygon':
              return `已绘制 ${geometry.coordinates.length} 个面`
            default:
              return '已绘制'
          }
        }

        // 兼容旧格式的数据
        if (typeof fieldValue === 'string') {
          const parsedValue = JSON.parse(fieldValue)
          if (Array.isArray(parsedValue)) {
            switch (item.problemType) {
              case '8': // 多线
                return `已绘制 ${parsedValue.length} 条线`
              case '10': // 多面
                return `已绘制 ${parsedValue.length} 个面`
              case '24': // 多点
                return `已绘制 ${parsedValue.length} 个点`
              default:
                return '已绘制'
            }
          }
        }
      } catch (e) {
        console.warn('Failed to parse draw status:', fieldValue)
      }

      return '已绘制'
    },

    cleanAreaListChildren(list) {
      if (!Array.isArray(list)) return
      list.forEach((item) => {
        if (Array.isArray(item.children)) {
          if (item.children.length === 0) {
            delete item.children
          } else {
            this.cleanAreaListChildren(item.children)
          }
        } else if (item.children == null) {
          delete item.children
        }
      })
    },

    initForm(formConfig, isEdit = true) {
      if (isEdit) {
        this.noneClick()
      }
      // this.noneClick()
      this.formData = {}
      this.formItems = []
      this.formRules = {}

      if (!formConfig || !formConfig.length) return

      const sortedItems = formConfig.sort((a, b) => a.orderIndex - b.orderIndex)

      sortedItems.forEach((question) => {
        if (question.areaList) {
          this.cleanAreaListChildren(question.areaList)
        }
        this.formItems.push({
          ...question,
          type: this.problemTypeMap[question.problemType],
        })

        let initialValue = ''
        if (question.problemResult) {
          if (question.problemType === '3') {
            initialValue = question.problemResult.split(',')
          } else if (question.problemType === '4') {
            initialValue = question.filePaths
              ? this.parseFilePaths(question.filePaths)
              : []
          } else if (
            ['8', '10', '24', '11', '27', '30'].includes(question.problemType)
          ) {
            try {
              const parsedData = JSON.parse(question.problemResult)
              initialValue = parsedData
              if (isEdit) {
                this.initBuildingAndDraw(parsedData, question)
              }
            } catch (e) {
              console.warn(
                'Failed to parse problemResult JSON:',
                question.problemResult
              )
              initialValue = ''
            }
          } else if (['26', '28', '29'].includes(question.problemType)) {
            initialValue = question.problemResult.split(',')
          } else {
            initialValue = question.problemResult
          }
        } else {
          if (question.problemType === '3') {
            initialValue = question.parentContentValue
              ? question.parentContentValue.split(',')
              : []
          } else if (question.problemType === '4') {
            initialValue = []
          } else if (
            ['8', '10', '24', '11', '27', '30'].includes(question.problemType)
          ) {
            this.currentDrawItem = question
            initialValue = ''
          } else if (['26', '28', '29'].includes(question.problemType)) {
            
            initialValue = []
          } else {
            initialValue = question.parentContentValue || ''
          }
        }

        this.$set(this.formData, question.pkid, initialValue)

        if (question.children && question.children.length > 0) {
          this.processChildren(question.children, question.pkid)
        }

        if (question.requireStatus === '1') {
          this.$set(this.formRules, question.pkid, [
            {
              required: true,
              message: question.hint || `请输入${question.problemContent}`,
              trigger: ['blur', 'change'],
            },
          ])

          if (question.problemType === '13') {
            this.formRules[question.pkid].push({
              pattern: /^\d+$/,
              message: '请输入整数',
              trigger: 'blur',
            })
          } else if (question.problemType === '14') {
            this.formRules[question.pkid].push({
              pattern: /^\d+(\.\d+)?$/,
              message: '请输入数字',
              trigger: 'blur',
            })
          } else if (question.problemType === '4' && question.limitCondition) {
            this.formRules[question.pkid].push({
              validator: (rule, value, callback) => {
                const minCount = parseInt(question.limitCondition)
                const currentCount = Array.isArray(value) ? value.length : 0
                if (currentCount < minCount) {
                  callback(new Error(`至少需要上传 ${minCount} 张照片`))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change'],
            })
          } else if (['26', '28', '29'].includes(question.problemType)) {
            // 添加区域选择层级验证
            this.formRules[question.pkid].push({
              validator: (rule, value, callback) => {
                if (!Array.isArray(value) || value.length === 0) {
                  callback(new Error('请选择区域'))
                  return
                }

                const requiredLevel = {
                  26: 3, // 社区级别需要选择3层（区-街道-社区）
                  28: 1, // 区级别只需要选择1层
                  29: 2, // 街道级别需要选择2层（区-街道）
                }[question.problemType]

                if (value.length < requiredLevel) {
                  const levelName = {
                    26: '社区',
                    28: '区',
                    29: '街道',
                  }[question.problemType]
                  callback(new Error(`请选择到${levelName}级别`))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change'],
            })
          }
        }
        if (!isEdit) {
          this.autoHighlightAndLocate(question)
        }
      })

      this.$nextTick(() => {
        if (this.$refs.editFormRef) {
          this.$refs.editFormRef.clearValidate()
        }
      })
    },

    processChildren(children, parentId, isEdit = true) {
      children.forEach((child) => {
        if (child.areaList) {
          this.cleanAreaListChildren(child.areaList)
        }
        this.formItems.push({
          ...child,
          type: this.problemTypeMap[child.problemType],
          parentId: parentId,
          parentContentIndex: child.parentContentIndex,
        })

        let childInitialValue = ''
        if (child.problemResult) {
          if (child.problemType === '3') {
            childInitialValue = child.problemResult.split(',')
          } else if (child.problemType === '4') {
            childInitialValue = child.filePaths
              ? this.parseFilePaths(child.filePaths)
              : []
          } else if (
            ['8', '10', '24', '11', '27', '30'].includes(child.problemType)
          ) {
            try {
              const parsedChildData = JSON.parse(child.problemResult)
              childInitialValue = parsedChildData
              if (isEdit) {
                this.initBuildingAndDraw(parsedChildData, child)
              }
            } catch (e) {
              console.warn(
                'Failed to parse child problemResult JSON:',
                child.problemResult
              )
              childInitialValue = ''
            }
          } else if (['26', '28', '29'].includes(child.problemType)) {
            childInitialValue = child.problemResult.split(',')
          } else {
            childInitialValue = child.problemResult
          }
        } else {
          if (child.problemType === '3') {
            childInitialValue = child.parentContentValue
              ? child.parentContentValue.split(',')
              : []
          } else if (child.problemType === '4') {
            childInitialValue = []
          } else if (
            ['8', '10', '24', '11', '27', '30'].includes(child.problemType)
          ) {
            childInitialValue = ''
          } else if (['26', '28', '29'].includes(child.problemType)) {
            childInitialValue = []
          } else {
            childInitialValue = child.parentContentValue || ''
          }
        }

        this.$set(this.formData, child.pkid, childInitialValue)

        if (child.children && child.children.length > 0) {
          this.processChildren(child.children, child.pkid)
        }

        if (child.requireStatus === '1') {
          this.$set(this.formRules, child.pkid, [
            {
              required: true,
              message: child.hint || `请输入${child.problemContent}`,
              trigger: ['blur', 'change'],
            },
          ])

          if (child.problemType === '13') {
            this.formRules[child.pkid].push({
              pattern: /^\d+$/,
              message: '请输入整数',
              trigger: 'blur',
            })
          } else if (child.problemType === '14') {
            this.formRules[child.pkid].push({
              pattern: /^\d+(\.\d+)?$/,
              message: '请输入数字',
              trigger: 'blur',
            })
          } else if (child.problemType === '4' && child.limitCondition) {
            this.formRules[child.pkid].push({
              validator: (rule, value, callback) => {
                const minCount = parseInt(child.limitCondition)
                const currentCount = Array.isArray(value) ? value.length : 0
                if (currentCount < minCount) {
                  callback(new Error(`至少需要上传 ${minCount} 张照片`))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change'],
            })
          } else if (['26', '28', '29'].includes(child.problemType)) {
            // 添加区域选择层级验证
            this.formRules[child.pkid].push({
              validator: (rule, value, callback) => {
                if (!Array.isArray(value) || value.length === 0) {
                  callback(new Error('请选择区域'))
                  return
                }

                const requiredLevel = {
                  26: 3, // 社区级别需要选择3层（区-街道-社区）
                  28: 1, // 区级别只需要选择1层
                  29: 2, // 街道级别需要选择2层（区-街道）
                }[child.problemType]

                if (value.length < requiredLevel) {
                  const levelName = {
                    26: '社区',
                    28: '区',
                    29: '街道',
                  }[child.problemType]
                  callback(new Error(`请选择到${levelName}级别`))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change'],
            })
          }
        }
      })
      
      // 新增项目时，确保建筑物选择功能正常工作
      if (!isEdit) {
        this.initBuildingSelectionForNewProject()
      }
    },

    // 新增项目时初始化建筑物选择功能
    initBuildingSelectionForNewProject() {
      // 确保特殊图层已加载，为建筑物选择做准备
      emitter.emit('CHECK_SPECIAL_LAYER_STATUS', (isChecked) => {
        if (!isChecked) {
          // 如果特殊图层未加载，先加载它
          emitter.emit('TOGGLE_SPECIAL_LAYER', true)
        }
      })
      
      // 初始化建筑物选择相关的状态
      this.selectedBuildings = []
      this.buildingPoints = []
      this.isBuildingSelectionMode = false
      this.currentBuildingItem = null
    },

    initBuildingAndDraw(drawData, question) {
      // emitter.emit('ClEAR_BUILDING_LABELS')
      // 设置currentDrawItem，这样getDrawMapData就能正确获取数据
      if (question && ['8', '10', '24'].includes(question.problemType)) {
        this.currentDrawItem = question
      }
      
      // 处理GeoJSON绘制数据
      if (drawData && drawData.type === 'Feature') {
        this.$nextTick(() => {
          if (this.$refs.drawMapToolRef) {
            this.$refs.drawMapToolRef.showExistingData({
              geoJsonData: drawData
            })
            // 跳转到绘制数据的中心点
            this.locateToDrawDataCenter(drawData)
            // 添加选择事件监听器
            this.addDrawSelectionListeners()
          }
        })
        return
      }

      if (
        Array.isArray(drawData) &&
        drawData[0] &&
        drawData[0].buildings &&
        drawData[0].buildings.length
      ) {
        this.selectedBuildings = drawData[0].buildings.map((id) => {
          return {
            id: id,
            name: `楼栋${id}`,
            type: 'building',
            properties: { id: id },
            layerId: '',
            coordinates: null,
          }
        })
        this.initDrawData = JSON.parse(JSON.stringify(drawData))
        this.checkAndToggleSpecialLayerForEcho(drawData[0].buildings, drawData[0].points)
      }
    },

    checkAndToggleSpecialLayerForEcho(buildingIds, pointsData) {
      emitter.emit('CHECK_SPECIAL_LAYER_STATUS', (isChecked) => {
        this.specialLayerWasChecked = isChecked

        if (!isChecked) {
          emitter.emit('TOGGLE_SPECIAL_LAYER', true)

          setTimeout(() => {
            this.highlightAndLocateBuildings(buildingIds, pointsData || [])
          }, 1000)
        } else {
          // 使用传入的点位数据
          this.highlightAndLocateBuildings(buildingIds, pointsData || [])
        }
      })
    },

    highlightAndLocateGeoJson(geojson) {
      if (geojson) {
        emitter.emit('HIGHLIGHT_GEOJSON', geojson)
        emitter.emit('LOCATE_TO_GEOJSON', geojson)
        this.activeGeoJson = geojson
      }
    },
    clearGeoJsonHighlight() {
      emitter.emit('CLEAR_HIGHLIGHT_GEOJSON')
      this.activeGeoJson = null
    },
    highlightAndLocateBuildings(buildingIds, points) {
      if (Array.isArray(buildingIds) && buildingIds.length) {
        // 在初始化时，不传递 deleteIds，避免覆盖用户的选择
        emitter.emit('UPDATE_SELECTED_BUILDINGS', {
          buildingIds,
          deleteIds: []
        })
        emitter.emit('LOCATE_TO_BUILDINGS', buildingIds)
        this.activeBuildingIds = buildingIds
      }
      
      // 如果有点位数据，也显示点位
      if (Array.isArray(points) && points.length) {
        const formattedPoints = points.map((point, index) => ({
          coordinates: point,
          id: Date.now() + index
        }))
        emitter.emit('UPDATE_BUILDING_POINTS', {
          points: formattedPoints,
          deletePoint: null
        })
      }
    },
    clearBuildingHighlight() {
      emitter.emit('CLEAR_SELECTED_BUILDINGS')
      emitter.emit('CLEAR_BUILDING_POINTS')
      this.activeBuildingIds = null
    },

    highlightAndLocateMarkers(markerCoords) {
      if (Array.isArray(markerCoords) && markerCoords.length) {
        emitter.emit('HIGHLIGHT_MARKERS', markerCoords)
        this.activeMarkers = markerCoords
      }
    },
    clearMarkerHighlight() {
      emitter.emit('CLEAR_HIGHLIGHT_MARKERS')
      this.activeMarkers = null
    },
    parseFilePaths(filePaths) {
      if (!Array.isArray(filePaths)) return []
      return filePaths.map((item, index) => ({
        name: item.fileName || `image_${index + 1}.jpg`,
        url: item.fileUrl,
        uid: item.pkid || Date.now() + index,
        id: item.pkid || item.fileUrl,
        raw: item,
      }))
    },
    removeFocusBeforeSwitch() {
      const el = document.activeElement
      if (el && el.tagName === 'INPUT' && el.type === 'radio') {
        el.blur()
      }
    },
    shouldShowChildItem(item) {
      this.removeFocusBeforeSwitch()
      if (
        !item.parentId ||
        item.parentContentIndex === null ||
        item.parentContentIndex === undefined
      ) {
        return true
      }

      const parentValue = this.formData[item.parentId]

      if (!parentValue) {
        return false
      }

      const parentItem = this.formItems.find(
        (formItem) => formItem.pkid === item.parentId
      )
      if (!parentItem || !parentItem.problemContentInfoList) {
        return false
      }

      const targetIndex = parseInt(item.parentContentIndex)

      if (parentItem.problemType === '2') {
        const selectedOption = parentItem.problemContentInfoList.find(
          (option) => option.pkid === parentValue
        )
        if (selectedOption) {
          return selectedOption.orderIndex === targetIndex
        }
      } else if (parentItem.problemType === '3') {
        if (Array.isArray(parentValue)) {
          return parentValue.some((value) => {
            const option = parentItem.problemContentInfoList.find(
              (opt) => opt.pkid === value
            )
            return option && option.orderIndex === targetIndex
          })
        }
      }

      return false
    },
    getRegionLabel(item, valueArr) {
      let options = item.areaList || this.cityOptions
      let labels = []
      let find = (opts, idx) => {
        if (!opts || idx >= valueArr.length) return
        let node = opts.find((o) => o.pkid == valueArr[idx])
        if (node) {
          labels.push(node.areaName)
          if (node.children && idx + 1 < valueArr.length) {
            find(node.children, idx + 1)
          }
        }
      }
      find(options, 0)
      return labels.join(' / ')
    },
    autoHighlightAndLocate(question) {
      if(['8','10'].includes(question.problemType)) {
        try {
          const geojson = typeof question.problemResult === 'string' ? JSON.parse(question.problemResult) : question.problemResult
          this.highlightAndLocateGeoJson(geojson)
        } catch(e) { /* ignore */ }
      }
      if (question.problemType === '24') {
        try {
          const geojson = typeof question.problemResult === 'string' ? JSON.parse(question.problemResult) : question.problemResult
          // 兼容 Feature/FeatureCollection
          let coords = []
          if (geojson && geojson.type === 'Feature' && geojson.geometry) {
            if (geojson.geometry.type === 'MultiPoint') {
              coords = geojson.geometry.coordinates
            } else if (geojson.geometry.type === 'Point') {
              coords = [geojson.geometry.coordinates]
            }
          } else if (geojson && geojson.type === 'FeatureCollection' && Array.isArray(geojson.features)) {
            geojson.features.forEach(f => {
              if (f.geometry.type === 'MultiPoint') {
                coords.push(...f.geometry.coordinates)
              } else if (f.geometry.type === 'Point') {
                coords.push(f.geometry.coordinates)
              }
            })
          }
          this.highlightAndLocateMarkers(coords)
        } catch(e) { /* ignore */ }
      }
      if(['11','30'].includes(question.problemType)) {
        try {
          const data = typeof question.problemResult === 'string' ? JSON.parse(question.problemResult) : question.problemResult
          if(Array.isArray(data) && data[0]) {
            const buildings = data[0].buildings || []
            const points = data[0].points || []
            this.highlightAndLocateBuildings(buildings, points)
          }
        } catch(e) { /* ignore */ }
      }
    },
    handleClearDraw(item) {
      // 清除当前选中的绘制内容
      if (this.$refs.drawMapToolRef) {
        // 确保绘制工具已初始化
        this.$refs.drawMapToolRef.ensureDrawInitialized()
        const draw = this.$refs.drawMapToolRef.getDraw()
        if (draw) {
          const ids = draw.getSelectedIds()
          
          
          if (ids && ids.length === 1) {
    
            
            // 先删除MapboxDraw要素
            draw.delete(ids)
            
            // 然后清除对应的显示要素（淡蓝色背景）
            this.$refs.drawMapToolRef.clearSpecificDisplayedFeature(ids[0])
            
            // 检查删除后的状态，如果没有任何要素了，清除表单数据
            setTimeout(() => {
              const remainingIds = draw.getSelectedIds()
              const allFeatures = draw.getAll()
              
              
              // 如果删除后没有任何要素了，清除表单数据
              if (allFeatures.features.length === 0 && this.currentDrawItem && this.currentDrawItem.pkid) {
                this.$set(this.formData, this.currentDrawItem.pkid, null)
              }
            }, 100)
            
            Message.success('已清除选中的绘制内容')
            // 更新选中状态
            this.checkSelectedDrawFeatures()
          } else if (ids && ids.length > 1) {
    
            Message.warning('请只选中一个要素进行删除')
          } else {
    
            Message.warning('请先选中要删除的要素')
          }
        }
      }
    },
    // 检查是否有选中的绘制要素
    checkSelectedDrawFeatures() {
      if (this.$refs.drawMapToolRef) {
        // 确保绘制工具已初始化
        this.$refs.drawMapToolRef.ensureDrawInitialized()
        const draw = this.$refs.drawMapToolRef.getDraw()
        if (draw) {
          const selectedIds = draw.getSelectedIds()
          this.hasSelectedDrawFeatures = selectedIds && selectedIds.length > 0
        } else {
          this.hasSelectedDrawFeatures = false
        }
      } else {
        this.hasSelectedDrawFeatures = false
      }
    },
    // 添加绘制选择事件监听器
    addDrawSelectionListeners() {
      if (this.$refs.drawMapToolRef) {
        // 确保绘制工具已初始化
        this.$refs.drawMapToolRef.ensureDrawInitialized()
        const draw = this.$refs.drawMapToolRef.getDraw()
        if (draw) {
          // 使用 SharedDrawingManager 的事件监听方法
          const sharedDrawingManager = require('@/utils/map/shared-drawing-manager.js').default
          sharedDrawingManager.addEventListener('draw.selectionchange', this.onDrawSelectionChange)
          sharedDrawingManager.addEventListener('draw.create', this.onDrawSelectionChange)
          sharedDrawingManager.addEventListener('draw.delete', this.onDrawSelectionChange)
          sharedDrawingManager.addEventListener('draw.update', this.onDrawSelectionChange)
        }
      }
    },
    // 移除绘制选择事件监听器
    removeDrawSelectionListeners() {
      if (this.$refs.drawMapToolRef) {
        // 确保绘制工具已初始化
        this.$refs.drawMapToolRef.ensureDrawInitialized()
        const draw = this.$refs.drawMapToolRef.getDraw()
        if (draw) {
          // 使用 SharedDrawingManager 的事件移除方法
          const sharedDrawingManager = require('@/utils/map/shared-drawing-manager.js').default
          sharedDrawingManager.removeEventListener('draw.selectionchange', this.onDrawSelectionChange)
          sharedDrawingManager.removeEventListener('draw.create', this.onDrawSelectionChange)
          sharedDrawingManager.removeEventListener('draw.delete', this.onDrawSelectionChange)
          sharedDrawingManager.removeEventListener('draw.update', this.onDrawSelectionChange)
        }
      }
    },
    // 绘制选择变化事件处理
    onDrawSelectionChange() {
      this.$nextTick(() => {
        this.checkSelectedDrawFeatures()
      })
    },
    handleClearAllDraw(item) {
      // 清除所有绘制内容
      if (this.$refs.drawMapToolRef) {
        // 使用clearAll方法，确保清除所有显示的内容（包括淡蓝色背景）
        this.$refs.drawMapToolRef.clearAll()
        
        // 清除对应的表单数据，防止重新绘制时显示之前的数据
        if (this.currentDrawItem && this.currentDrawItem.pkid) {
          this.$set(this.formData, this.currentDrawItem.pkid, null)
        }
        
        Message.success('已清除所有绘制内容')
        // 更新选中状态
        this.checkSelectedDrawFeatures()
      }
    },
    handleEndDraw(item) {
      this.$emit('end-draw', item)
    },

    // 跳转到绘制数据的中心点
    locateToDrawDataCenter(drawData) {
      if (!drawData || !drawData.geometry) return
      
      const geometry = drawData.geometry
      let center = null
      let zoom = 14
      
      try {
        switch (geometry.type) {
          case 'Point':
            center = geometry.coordinates
            zoom = 16
            break
          case 'MultiPoint':
            // 计算多点中心
            if (geometry.coordinates && geometry.coordinates.length > 0) {
              let totalLng = 0
              let totalLat = 0
              geometry.coordinates.forEach(coord => {
                totalLng += coord[0]
                totalLat += coord[1]
              })
              center = [totalLng / geometry.coordinates.length, totalLat / geometry.coordinates.length]
              zoom = 15
            }
            break
          case 'LineString':
            // 计算线的中心点
            if (geometry.coordinates && geometry.coordinates.length > 0) {
              const midIndex = Math.floor(geometry.coordinates.length / 2)
              center = geometry.coordinates[midIndex]
              zoom = 15
            }
            break
          case 'MultiLineString':
            // 计算多线的中心点
            if (geometry.coordinates && geometry.coordinates.length > 0) {
              let totalLng = 0
              let totalLat = 0
              let totalCount = 0
              
              geometry.coordinates.forEach(line => {
                if (line && line.length > 0) {
                  const midIndex = Math.floor(line.length / 2)
                  totalLng += line[midIndex][0]
                  totalLat += line[midIndex][1]
                  totalCount++
                }
              })
              
              if (totalCount > 0) {
                center = [totalLng / totalCount, totalLat / totalCount]
                zoom = 14
              }
            }
            break
          case 'Polygon':
            // 计算多边形的中心点
            if (geometry.coordinates && geometry.coordinates.length > 0) {
              const ring = geometry.coordinates[0]
              if (ring && ring.length > 0) {
                let totalLng = 0
                let totalLat = 0
                ring.forEach(coord => {
                  totalLng += coord[0]
                  totalLat += coord[1]
                })
                center = [totalLng / ring.length, totalLat / ring.length]
                zoom = 14
              }
            }
            break
          case 'MultiPolygon':
            // 计算多边形的中心点
            if (geometry.coordinates && geometry.coordinates.length > 0) {
              let totalLng = 0
              let totalLat = 0
              let totalCount = 0
              
              geometry.coordinates.forEach(polygon => {
                if (polygon && polygon.length > 0) {
                  const ring = polygon[0]
                  if (ring && ring.length > 0) {
                    ring.forEach(coord => {
                      totalLng += coord[0]
                      totalLat += coord[1]
                    })
                    totalCount += ring.length
                  }
                }
              })
              
              if (totalCount > 0) {
                center = [totalLng / totalCount, totalLat / totalCount]
                zoom = 13
              }
            }
            break
        }
        
        if (center) {
          // 发送跳转事件
          emitter.emit('FLY_TO_CENTER', {
            center: center,
            // zoom: zoom,
            duration: 2000
          })
        }
      } catch (error) {
        console.error('计算绘制数据中心点失败:', error)
      }
    },
  },
  beforeDestroy() {
    this.clearGeoJsonHighlight()
    this.clearBuildingHighlight()
    this.clearMarkerHighlight() // 新增
    if (this.isBuildingSelectionMode) {
      this.exitBuildingSelectionMode()
    }
    this.closeBuildingMode()

    emitter.emit('REMOVE_SELECTED_BUILDINGS')
  },
}
</script>

<style lang="scss" scoped>
.edit-mode {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;

  .edit-header {
    flex-shrink: 0; 
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid #e8e8e8;

    .edit-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      .edit-title-text {
        vertical-align: middle;
        display: inline-block;
        max-width: 240px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .edit-status {
        vertical-align: middle;
        border-radius: 4px;
        padding: 2px 4px;
        background: #e6f3ff;
        color: #fff;
        font-size: 12px;
        margin-left: 10px;

        &.add-status {
          background: #f6ffed;
          color: #52c41a;
        }
      }
    }

    .edit-subtitle {
      font-size: 12px;
      color: #999;
      margin-left: 8px;
    }

    .edit-actions {
      display: flex;
      gap: 8px;
      position: relative;
      z-index: 10;
      pointer-events: auto;
      
      .el-button {
        pointer-events: auto;
      }
    }
  }
  .edit-form-container {
    height: 100%;
    overflow-y: auto;
    flex: 1;
  } 

  .edit-form {
    padding: 16px 20px;
    

    :deep(.el-form-item) {
      margin-bottom: 16px;

      .el-form-item__label {
        padding-bottom: 0;
      }

      .el-input {
        width: 100%;
        .el-input__inner {
          height: 32px;
          line-height: 32px;
          &[type='number'] {
            -moz-appearance: textfield;
            &::-webkit-outer-spin-button,
            &::-webkit-inner-spin-button {
              -webkit-appearance: none;
              margin: 0;
            }
          }
        }
      }

      .el-textarea {
        width: 100%;
        .el-textarea__inner {
          padding: 8px 12px;
        }
      }

      .el-radio-group {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        .el-radio {
          margin-right: 0;
          line-height: 1.4;
          white-space: normal;
          word-break: break-word;
          max-width: 355px;
          display: flex;
          align-items: flex-start;
          .el-radio__input {
            margin-top: 2px;
            flex-shrink: 0;
          }
          .el-radio__label {
            white-space: normal;
            word-break: break-word;
            line-height: 1.4;
            padding-left: 8px;
          }
        }
      }

      .el-checkbox-group {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        .el-checkbox {
          margin-right: 0;
          line-height: 1.4;
          white-space: normal;
          word-break: break-word;
          max-width: 355px;
          display: flex;
          align-items: flex-start;
          .el-checkbox__input {
            margin-top: 2px;
            flex-shrink: 0;
          }
          .el-checkbox__label {
            white-space: normal;
            word-break: break-word;
            line-height: 1.4;
            padding-left: 8px;
          }
        }
      }

      .el-upload {
        &.el-upload--picture-card {
          width: 100px;
          height: 100px;
          line-height: 100px;
        }
      }
      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 100px;
          height: 100px;
          &.is-ready {
            display: none;
          }
        }
      }

      .el-button {
        min-width: 120px;
      }

      .el-cascader {
        width: 100%;
      }
    }

    .draw-info,
    .building-info,
    .floor-info {
      margin-left: 12px;
      font-size: 13px;
      color: #67c23a;
    }

    .building-selection-container {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;

      .building-info {
        margin-left: 0;
        margin-top: 8px;
        font-weight: 500;
      }

      .el-button {
        min-width: 100px;
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 12px;
      margin-top: 24px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
    }

    .upload-limit {
      font-size: 12px;
      color: #909399;
      margin-top: 8px;
      line-height: 1.4;
    }
  }
}
</style>
